Ext.define('EM.controller.Folders', {
    extend:'Ext.app.Controller',
    models:['Folder'],
    stores:['Folders'],
    views:['Viewport'],
    FoldersStore:Ext.getStore("Folders"),

    init:function () {

        var me = this;

        me.status = {ACTIVE:1, INACTIVE:0, REMOVED:-1, SEARCHRESULT:-1, PARENT_INACTIVE:2};

        me.control({
            '#folders-treeview > treeview':{
                beforedrop:function (node, data, overModel, dropPosition, dropFunction, eOpts) {
                    if (overModel.data.id == -1)
                        return false;
                },
                drop:function (node, data, overModel, dropPosition, dropFunction) {
                    var parentId = overModel.data.id;
                    var records = data.records;
                    for (var i = 0; i < records.length; i++) {
                        records[i].set('parentId', parentId);
                    }
                    this.getStore("Folders").sync();
                }
            },
            '#folders-treeview':{
                itemclick:function (view, record, item, index, e, eOpts) {

                },
                itemcontextmenu:function (view, record, item, index, e, eOpts) {
                    e.preventDefault();
                    var status = record.data.status;
                    var id = record.data.id;
                    var inactive = !(status === me.status.ACTIVE);

                    Ext.create('Ext.menu.Menu', {
//                        id:'folder-menu',
                        items:[
                            {
                                text:'Reload',
                                listeners:{
                                    click:function () {
                                        me.reloadFolder(record);
                                    }
                                }
                            },
                            {
                                text:'Delete',
                                hidden:id < 1,
                                listeners:{
                                    click:function () {
                                        me.removeFolder(record);
                                    }
                                }
                            },
//                            {
//                                text:"Restore all",
//                                hidden:id != -1,
//                                listeners:{
//                                    click:function () {
//                                        me.restoreAllFolders();
//                                    }
//                                }
//                            },
                            {
                                text:'Restore',
                                hidden:(!inactive) || id < 1,
                                listeners:{
                                    click:function () {
                                        me.restoreFolder(record);
                                    }
                                }
                            },
                            {
                                text:'Duplicate',
                                hidden:inactive || id < 1
                            },
                            {
                                xtype:'menuseparator',
                                hidden:id < 1 || inactive
                            },
                            {

                                xtype:'textfield',
                                hidden:id < 1 || inactive,
                                emptyText:'Rename',
                                width:30,
                                iconCls:'no-icon',
                                selectOnFocus:true,
                                enableKeyEvents:true,
                                listeners:{
                                    specialkey:function (field, e, eOps) {
                                        if (e.getKey() === e.ENTER) {
                                            field.up().destroy();
                                            me.updateFolder(record, 'text', field.getValue());
                                        }
                                    }
                                }
                            },
                            {
                                xtype:'textfield',
                                emptyText:'New...',
                                hidden:id == -1 || inactive,
                                width:30,
                                iconCls:'no-icon',
                                selectOnFocus:true,
                                enableKeyEvents:true,
                                listeners:{
                                    specialkey:function (field, e, eOps) {
                                        if (e.getKey() === e.ENTER) {
                                            field.up().destroy();
                                            me.addFolder(record, field.getValue());
                                        }
                                    }
                                }
                            }
                        ]
                    }).showAt(e.getXY());
                },
                containercontextmenu:function (view, e, eOpts) {
                    e.preventDefault();
                }
            },

            '#folders-search-textfield':{
                keyup:function (field, e) {

                    var value = field.getValue();
                    var rn = field.up('panel').down('treepanel').getRootNode();
                    var searchNode;


//                    if (value.length > 0) {
//
//                        var resultArray = [];
//                        var i = 0;
//
//                        var active = rn.findChild('fid', 0);
//                        active.cascadeBy(function () {
//                            if (this.data.fid > 0) {
//                                if (this.data.text.toLowerCase().indexOf(value.toLowerCase()) > -1) {
//                                    resultArray[i++] = this;
//                                }
//                            }
//                        });
//
//                        if (searchNode = rn.findChild('text', 'Search')) {
//                            searchNode.removeAll();
//                        } else {
//                            searchNode = rn.appendChild({text:'Search', expanded:true, children:[], iconCls:'x-tree-node-icon', fid:-2, id:-2});
//                        }
//
//                        for (var j = 0; j < i; j++) {
//                            var nd = searchNode.appendChild(resultArray[j].data);
//                            nd.data.status = me.status.SEARCHRESULT;
//                        }
//                    } else {
//                        if (searchNode = rn.findChild('text', 'Search')) {
//                            rn.removeChild(searchNode);
//                        }
//                    }
                },
                specialkey:function (field, e) {
                    if (e.getKey() === e.ESC) {
                        field.reset();
                    }
                }
            }
        });

    },

    addFolder:function (node, name) {
        node.expand();
        node.appendChild({text:name, parentId:node.data.id, children:[]});
        this.getStore("Folders").sync();
    },

    removeFolder:function (node) {
        var me = this;
        if (node.data.status == this.status.ACTIVE) {
            node.set('status', this.status.INACTIVE);
            Ext.getCmp('folders-treeview').getRootNode().findChild('id', -1).appendChild(node);
            this.getStore("Folders").sync();
        } else if (node.data.status == this.status.INACTIVE) {
            Ext.Msg.show({
                title:'Delete folder',
                msg:'Are you sure to permanently delete this folder?',
                buttons:Ext.Msg.YESNO,
                icon:Ext.Msg.QUESTION,
                fn:function (buttonId) {
                    if (buttonId == "yes") {
                        node.set('status', me.status.REMOVED);
                        me.getStore("Folders").sync();
                        node.remove(true);
                    }
                }
            });
        }
    },

    restoreFolder:function (node) {
        var myFolders = Ext.getCmp('folders-treeview').getRootNode().findChild('id', 0);
        node.set('status', this.status.ACTIVE);
        this.getStore("Folders").sync();
        node.remove(false);
    },

    updateFolder:function (node, key, value) {
        node.set(key, value);
        this.getStore("Folders").sync();
    },

    reloadFolder:function (node) {
        node.removeAll(false);
        this.getStore("Folders").load({node:node});
    },

    restoreAllFolders:function () {
        var recycleBin = Ext.getCmp('folders-treeview').getRootNode().findChild('id', -1);
        var removed = recycleBin.childNodes;
        var me = this;
        for (var i = 0; i < removed.length; i++) {
            removed[i].set('status', me.status.ACTIVE);
            console.log(removed[i]);
            this.getStore("Folders").sync();
        }
        recycleBin.removeAll();
    }
});
